package com.fyy.im.client;

import com.fyy.im.message.*;
import com.fyy.im.protocol.MessageCodecSharable;
import com.fyy.im.protocol.ProcotolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Author fyy
 * @Description 聊天室客户端
 * @Date 2021/5/11 15:44
 */
@Slf4j
public class ChatClient {

    public static void main(String[] args) {
        NioEventLoopGroup worker = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        CountDownLatch WAIT_FOR_LOGIN = new CountDownLatch(1);
        AtomicBoolean LOGIN = new AtomicBoolean(false);
        AtomicBoolean EXIT = new AtomicBoolean(false);
        Scanner scanner = new Scanner(System.in);
        try {
            Bootstrap client = new Bootstrap();
            client.channel(NioSocketChannel.class);
            client.group(worker);
            client.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel sc) throws Exception {
                    ChannelPipeline line = sc.pipeline();
                    line.addLast(new ProcotolFrameDecoder());
                    line.addLast(LOGGING_HANDLER);
                    line.addLast(MESSAGE_CODEC);
                    //用于判断是不是读\写空闲时间过长
                    //3s内如果没有向服务器写数据，会触发一个IdleState#WRITEER_IDLE事件
                    line.addLast(new IdleStateHandler(0,3,0));
                    //ChannelDuplexHandler 可以同时作为入站和出站处理器
                    line.addLast(new ChannelDuplexHandler(){
                        //用来触发特殊事件
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            IdleStateEvent event = (IdleStateEvent) evt;
                            //触发了写空闲事件
                            if(event.state() == IdleState.WRITER_IDLE){
//                                ctx.writeAndFlush(new PingMessage());
                            }
                        }
                    });
                    //入站处理
                    line.addLast("ChatClient Handler",new ChannelInboundHandlerAdapter(){

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            log.debug("消息:{}",msg);
                            if(msg instanceof LoginResponseMessage){
                                LoginResponseMessage response = (LoginResponseMessage) msg;
                                if(response.isSuccess()){ //登录成功
                                    LOGIN.set(true);
                                }
                                WAIT_FOR_LOGIN.countDown(); //唤醒system in线程
                            }
                        }

                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            //负责接收用户在控制台的输入,负责向服务器发送各种消息
                            new Thread(() -> {
                                System.out.println("请输入用户名：");
                                String username = scanner.nextLine();
                                if(EXIT.get()){
                                    return;
                                }
                                System.out.println("请输入密码：");
                                String password = scanner.nextLine();
                                if(EXIT.get()){
                                    return;
                                }
                                //构造消息对象
                                LoginRequestMessage message = new LoginRequestMessage(username,password);
                                System.out.println(message);
                                //发送消息
                                ctx.writeAndFlush(message);
                                System.out.println("等待后续操作..... .......");
                                try {
                                    WAIT_FOR_LOGIN.await();
                                }catch (Exception e){
                                    log.error("处理登录异常:{}",e.getMessage());
                                }
                                if(!LOGIN.get()){
                                    ctx.channel().close();
                                    return;
                                }
                                while (true){
                                    System.out.println("===========================================");
                                    System.out.println("send [username] [content]");
                                    System.out.println("gsend [group name] [content]");
                                    System.out.println("gcreate [group name] [m1,m2,m3...]");
                                    System.out.println("gmembers [group name]");
                                    System.out.println("gjoin [group name]");
                                    System.out.println("gquit [group name]");
                                    System.out.println("quit");
                                    System.out.println("===========================================");
                                    String command = null;
                                    try {
                                        command = scanner.nextLine();
                                    }catch (Exception e){
                                        log.error("指令获取异常:{}",e.getMessage());
                                        break;
                                    }
                                    if(EXIT.get()){
                                        return;
                                    }
                                    String[] s = command.split(" ");
                                    switch (s[0]){
                                        case "send":
                                            ctx.writeAndFlush(new ChatRequestMessage(username,s[1],s[2]));
                                            break;
                                        case "gsend":
                                            ctx.writeAndFlush(new GChatRequestMessage(username,s[1],s[2]));
                                            break;
                                        case "gcreate":
                                            Set<String> set = new HashSet<>(Arrays.asList(s[2].split(",")));
                                            set.add(username);
                                            ctx.writeAndFlush(new GCRequestMessage(s[1],set));
                                            break;
                                        case "gjoin":
                                            ctx.writeAndFlush(new GJRequestMessage(username,s[1]));
                                            break;
                                        case "gmembes":
                                            ctx.writeAndFlush(new GMRequestMessage(s[1]));
                                            break;
                                        case "gquit":
                                            ctx.writeAndFlush(new GQRequestMessage(username,s[1]));
                                            break;
                                        case "quit":
                                            ctx.channel().close();
                                            return;
                                    }
                                }
                            },"system in").start();
                        }

                        @Override
                        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                            log.debug("连接已经断开,按任意键退出..... ..... ");
                            EXIT.set(true);
                        }

                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                            log.debug("连接已经断开,按任意键退出..... {}",cause.getMessage());
                            EXIT.set(true);
                        }
                    });

                }
            });
            ChannelFuture future = client.connect("127.0.0.1", 8080).sync();
            future.channel().closeFuture().sync();
        }catch (Exception e){
            log.error("【聊天室】客户端服务异常:{}",e.getMessage());
        }finally {
            worker.shutdownGracefully();
        }

    }

}
